<?php

declare(strict_types=1);

namespace app\model;

use  think\Exception;
use think\model\concern\SoftDelete;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id 自增id
 * @property int $agent_id 代理商id
 * @property string $name 渠道名
 * @property bool $state 1 生效 2失效
 * @property float $mobile_discount_slow 话费慢充折扣
 * @property int $mobile_status_slow 慢充状态：1启用 2禁用
 * @property float $mobile_discount_fast 快充折扣
 * @property int $mobile_status_fast 快充状态：1启用 2禁用
 * @property int $slow_order_num 慢充订单数量
 * @property int $slow_order_amount 慢充订单总金额
 * @property int $fast_order_num 快充订单数量
 * @property int $fast_order_amount 快充订单总金额
 * @property int $total_order_num 订单数量【慢充+快充】
 * @property int $total_order_amount 订单总额【慢充+快充】
 * @property string $remark 标记
 * @property int $is_deleted 是否删除：0否 1是
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property int $template_id 模板id
 * @property string $deleted_at 删除时间
 * @property-read \app\model\ChannelServDiscount[] $serv_discount
 * @property-read \app\model\Agent $agent
 * @property-read \app\model\MobileRechargeStatistics[] $success_statics
 * @property-read \app\model\Template $template
 * @property int $order_display_status 订单入口显示状态 1 显示 2关闭
 * @property-read mixed $template_url
 * @property bool $is_sys 是否系统生成 0否 1是
 * @property int $channel_type 渠道类型
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class AgentChannel extends CommonModel
{
    use SoftDelete;

    protected $append = ['template_url'];

    const YMHC_ADMIN_CHANNEL = 'ymhcadmin';

    //有美生活小程序渠道名称
    const YMSH_CHANNEL_XIAOCHENGXU = 'xiaochengxu';

    const STATE_ACTIVE = 1; //有效
    const STATE_CLOSE = 2; //失效

    const IS_SYS_ACTIVE = 1; //有效
    const IS_SYS_CLOSE = 0; //失效

    const CHANNEL_TYPE_BRAND_EXTENSION = 1;//权益品牌默认推广
    const CHANNEL_TYPE_YMSH = 2;//有美生活新建本地生活渠道

    /*
    渠道业务折扣
    */
    public function servDiscount()
    {
        return $this->hasMany(ChannelServDiscount::class, 'channel_id');
    }

    /* 归属代理商 */
    public function agent()
    {
        return $this->belongsTo(Agent::class, 'agent_id', 'id');
    }

    /**
     * 模板
     * @return \think\model\relation\HasOne
     */
    public function template()
    {
        return $this->hasOne(Template::class, 'id', 'template_id');
    }

    /**
     * 搜索模板
     */
    public function searchTemplateIdAttr($query, $value)
    {

        $template_id = $value ?? '';

        $query->when($template_id, function ($query) use ($template_id) {
            $query->where('template_id', $template_id);
        });

    }

    /**
     * 搜索模板
     */
    public function searchNameAttr($query, $value, $params)
    {

        $template_name = $params['name'] ?? '';

        $query->when($template_name, function ($query) use ($template_name) {
            $query->where('name', 'like', '%' . $template_name . '%');
        });


    }

    /**
     * 获取模板链接
     */
    public function getTemplateUrlAttr()
    {
        /**
         * @var Agent $agent
         */
        $agent = Agent::query()->where('id', $this->agent_id)->cache('agent_cache_' . $this->agent_id, 10)->find();

        $host = '';
        $pre_url = '';
        if (!empty($this->template)) {
            $pre_url = $this->template->pre_url . '?channel=' . $this->getAttr('name');
        }

        if ($agent && $agent->link_type == Agent::LINK_TYPE_KUAIZHAN) {
            $config = Config::where('type', 'h5_host_url')->column('value', 'field');
            $h5_host_url = $config['h5_host_url'];
            $host = $h5_host_url;

            if (strstr($pre_url, 'jxcall/index')) {//话费
                return $config['h5_host_url_cps_mobile'] . '?channel=' . $this->getAttr('name');
            }

            $pre_url = str_replace('/topup', '', $pre_url);
        } else {
            $host = env('app.API_URL');
        }


        return $host . $pre_url;
    }


    /*
     成功率统计相关
    */
    public function successStatics()
    {
        return $this->hasMany(MobileRechargeStatistics::class, 'channel_id');
    }

    public static function onAfterDelete($model)
    {
        // 同步is_deleted
        self::withTrashed()->update(['is_deleted' => 1, 'id' => $model->id]);
        // 删除渠道下折扣配置
        ChannelServDiscount::where('channel_id', $model->id)->delete();
    }

    /*
     创建时候同步生成 报表数据
    */
    public static function onAfterCreate($model)
    {
        // 成功率表
        //$model->is_deleted = 1;
        //$model->save();
    }

    /**
     * 渠道是否存在服务
     * @param $type
     */
    public function hasServType($serv_type)
    {

        $agentServiceConfig = ChannelServDiscount::where('channel_id', $this->id)
            ->where('serv_type', $serv_type)
            ->where('state', ChannelServDiscount::STATUS_ACTIVE)
            ->find();

        $templateservice = false;
        //同时这个模板是否开启了入口
        if (in_array($serv_type, [
            PRODUCT_COUPON_SERV,
            PRODUCT_TRAVEL_OIL_SERV,
            PRODUCT_FOOD_SHOP_SERV,
            PRODUCT_SECKILL_SERV
        ])) {
            $templateObj = Template::query()->where('template_name', '品牌权益')->find();
            if (empty($templateObj)) {
                throw new Exception('总后台模板缺少品牌权益');
            }

            $templateservice = TemplateService::where('template_id', $templateObj->id)
                ->where('serv_type', $serv_type)->find();
        }

        return $agentServiceConfig && $templateservice;
    }

    /**
     * 随机渠道名称，并且是唯一的
     */
    public function getRandomChannelName()
    {
        $str = randomString(6, 0);
        $info = self::query()->where('name', trim($str))->find();
        if ($info) {
            self::getRandomChannelName();
        }
        return $str;
    }

    /**
     * 公用模板
     * @param $channel_id
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommonChannelTemplateService($channel_id)
    {
        if (ChannelServDiscount::query()->where('channel_id', $channel_id)->find()) return false;
        $channelInfo = AgentChannel::query()->where('name', AgentChannel::YMSH_CHANNEL_XIAOCHENGXU)->find();
        if (!$channelInfo) return false;


        /**@var AgentChannel $channelInfo**/
        ChannelServDiscount::query()
            ->where('channel_id', $channelInfo->id)
            ->select()->each(function (ChannelServDiscount $channelServDiscount) use ($channel_id) {
                $insert = $channelServDiscount->toArray();
                unset($insert['id']);
                unset($insert['created_at']);
                unset($insert['updated_at']);
                $insert['channel_id'] = $channel_id;
                (new ChannelServDiscount($insert))->save();
            });
    }


}
